<script setup>
import {
  Modal as AModal,
  Table as ATable,
  Button as AButton,
  Form as AForm,
  FormItem as AFormItem,
  DatePicker as ADatePicker,
  Popconfirm as APopconfirm,
  message
} from 'ant-design-vue'
import { ref, reactive, onMounted } from 'vue'
import { putDelete, savePersonStatusList, putHistory } from '@/api/claim'
/**
 * ant-design-vue将英文改为中文 DatePicker日期控件
 * https://blog.csdn.net/qq2754289818/article/details/130972771
 */
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
dayjs.locale('zh-cn')
const disabledDate = (current) => {
  // Can not select days before today and today
  return current && current < dayjs().startOf('day')
}
const rules = {
  startDate: [{ required: true, message: '请选择挂起开始日期', trigger: 'change' }]
}
const dateFormat = 'YYYY-MM-DD'
const props = defineProps({
  operatorId: {
    type: String,
    default: ''
  },
  operatorName: {
    type: String,
    default: ''
  },
  groupNo: {
    type: String,
    default: ''
  }
})
const modalVisible = defineModel()
const loading = ref(false)
const emit = defineEmits(['updateTable'])
const suspendFormRef = ref()
async function add() {
  suspendFormRef.value
    .validate()
    .then(async () => {
      console.log('props', props)
      let res = null
      const data = {
        startDate: formState.startDate,
        endDate: formState.endDate,
        list: [
          {
            groupNo: props.groupNo,
            operatorId: props.operatorId,
            operatorName: props.operatorName
          }
        ]
      }
      try {
        res = await savePersonStatusList(data)
      } catch (err) {
        console.log('err', err)
      }
      if (res?.success == '0') {
        initData()
        message.success('新增成功')
      }
    })
    .catch((error) => {
      console.log('error', error)
    })
}
function initData() {
  pagination.current = 1
  getTableList()
}
onMounted(() => {
  initData()
})
const formState = reactive({
  startDate: '',
  endDate: ''
})
// 获取tabledata
const columns = [
  {
    title: '序号',
    width: 70,
    dataIndex: 'Index',
    customRender: ({ text, record, index }) => `${index + 1}`
  },
  {
    title: '挂起开始日期',
    dataIndex: 'pendingStartDate'
  },
  {
    title: '挂起结束日期',
    dataIndex: 'pendingEndDate'
  },
  {
    title: '操作',
    key: 'operation',
    width: 100
  }
]
const pagination = reactive({
  current: 1,
  pageSize: 15,
  defaultPageSize: 15,
  pageSizeOptions: ['15', '30', '50', '100'],
  showSizeChanger: true,
  total: 0,
  onChange: handlePageChange
  // hideOnSinglePage: true
})
function handlePageChange(page, pageSize) {
  pagination.current = page
  pagination.pageSize = pageSize
  getTableList()
}
const dataSource = ref([])
async function getTableList() {
  loading.value = true
  const data = {
    operatorId: props.operatorId,
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    groupNo: props.groupNo
  }
  let res = null
  try {
    res = await putHistory(data)
  } catch (err) {
    console.log('err', err)
  } finally {
    loading.value = false
  }
  if (res?.success == '0') {
    pagination.total = res.data.total
    dataSource.value = res.data.list
  }
}

// 操作
async function handleUpdate(record) {
  const { pendingEndDate, pendingStartDate, id } = record
  if (!pendingStartDate) {
    message.error('挂起开始日期不能为空')
    return
  }
  const start = dayjs(pendingStartDate)
  const end = dayjs(pendingEndDate)
  const diff = end.diff(start)
  console.log('diff', diff)
  if (diff < 0) {
    message.error('不允许结束日期小于开始日期')
    return
  }
  let res = null
  const data = {
    startDate: pendingStartDate,
    endDate: pendingEndDate,
    list: [
      {
        id,
        operatorId: props.operatorId,
        operatorName: props.operatorName
      }
    ]
  }
  try {
    res = await savePersonStatusList(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.success == '0') {
    initData()

    message.success('修改成功')
  }
}
async function handleDelete(record) {
  let res = null
  try {
    res = await putDelete({ id: record.id })
  } catch (err) {
    console.log('err', err)
  }
  if (res?.success == '0') {
    initData()
    message.success('删除成功')
  }
}
function handleCancel() {
  modalVisible.value = false
  emit('updateTable')
}
</script>
<template>
  <a-modal
    v-model:open="modalVisible"
    :maskClosable="false"
    :keyboard="false"
    @cancel="handleCancel"
    width="880px"
    title="挂起编辑"
  >
    <template #footer>
      <div class="footer-modal">
        <a-button key="back" @click="handleCancel">关闭</a-button>
      </div>
    </template>
    <a-form
      :model="formState"
      ref="suspendFormRef"
      :rules="rules"
      class="suspendForm"
      layout="inline"
      autocomplete="off"
    >
      <a-form-item label="挂起开始日期" name="startDate">
        <a-date-picker
          :locale="locale"
          :format="dateFormat"
          :disabledDate="disabledDate"
          :valueFormat="dateFormat"
          v-model:value="formState.startDate"
        />
      </a-form-item>
      <a-form-item label="挂起结束日期" name="endDate">
        <a-date-picker
          :locale="locale"
          :format="dateFormat"
          :valueFormat="dateFormat"
          :disabledDate="disabledDate"
          v-model:value="formState.endDate"
        />
      </a-form-item>
      <a-form-item>
        <a-button class="search-btn" type="primary" @click="add">新增</a-button>
      </a-form-item>
    </a-form>
    <a-table
      :scroll="{ x: 700, y: 400 }"
      :data-source="dataSource"
      size="small"
      class="ant-table-striped"
      bordered
      :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
      :pagination="pagination"
      :loading="loading"
      :columns="columns"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'pendingStartDate'">
          <a-date-picker
            :locale="locale"
            :format="dateFormat"
            :disabledDate="disabledDate"
            :valueFormat="dateFormat"
            v-model:value="record.pendingStartDate"
          />
        </template>
        <template v-if="column.dataIndex === 'pendingEndDate'">
          <a-date-picker
            :locale="locale"
            :format="dateFormat"
            :disabledDate="disabledDate"
            :valueFormat="dateFormat"
            v-model:value="record.pendingEndDate"
          />
        </template>
        <template v-if="column.key === 'operation'">
          <span class="operation" @click="handleUpdate(record)">修改</span>
          <a-popconfirm
            title="确认删除?"
            ok-text="确认"
            cancel-text="取消"
            @confirm="handleDelete(record)"
          >
            <a class="delete">删除</a>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
  </a-modal>
</template>
<style lang="scss" scoped>
.suspendForm {
  margin-bottom: 20px;
}
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
}
.ant-table-striped :deep(.ant-table-thead) > tr > th {
  background-color: #fafafa;
}
.operation {
  color: #459df8;
  cursor: pointer;
  margin-right: 12px;
  &:hover {
    background-color: hsla(160, 100%, 37%, 0.2);
  }
}
.delete {
  color: #459df8;
  cursor: pointer;
}
</style>
